package com;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class  TestLock{
    private HashMap<String,Object> map = new HashMap();
    private ReadWriteLock rwl = new ReentrantReadWriteLock();
    public  void wirteLock(){
        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread()+ "正在写入");
            TimeUnit.MILLISECONDS.sleep(50);
            System.out.println(Thread.currentThread()+"写入完成");
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            rwl.writeLock().unlock();
        }
    }
    public  void  readLock(){
           rwl.readLock().lock();
           try {
               System.out.println(Thread.currentThread()+ "正在读取");
               TimeUnit.MILLISECONDS.sleep(50);
               System.out.println(Thread.currentThread()+"读取完成");
           }catch(Exception e){
                   e.printStackTrace();
           }finally {
               rwl.readLock().unlock();
           }
    }

}
public class TestReadWriteLock {
    public static void main(String[] args) {
        TestLock testLock = new TestLock();
        for (int i = 0; i <5; i++) {
            new Thread(()->{
                testLock.readLock();
            },i+"").start();
            new Thread(()->{
                testLock.wirteLock();
            }).start();
        }
    }
}
